import requests
import sys
import urllib.parse
import json

API_KEY = ""
SECRET_KEY = ""

def read_config(config_file_path, api_key, secret_key):
    """
    从配置文件中读取 API_KEY 和 SECRET_KEY
    :param file_path: 配置文件的路径
    :return: (API_KEY, SECRET_KEY)
    """

    try:
        with open(config_file_path, 'r') as file:
            for line in file:
                line = line.strip()
                if line.startswith("API_KEY"):
                    api_key = line.split('=')[1].strip().strip('"')
                elif line.startswith("SECRET_KEY"):
                    secret_key = line.split('=')[1].strip().strip('"')
    except FileNotFoundError:
        print(f"错误：文件 {config_file_path} 未找到。")
    except Exception as e:
        print(f"读取配置文件时发生错误：{e}")

    return api_key, secret_key

def main():
    # 接收传入的模型回复
    if len(sys.argv) < 2:
        print("Error: No model reply provided", file=sys.stderr)
        sys.exit(1)

    model_reply = sys.argv[1]  # 获取第一个命令行参数

    # model_reply = "你好，我叫小度"

     # 对模型回复进行 UTF-8 编码并进行 URL 编码
    encoded_model_reply = urllib.parse.quote_plus(model_reply.encode('utf-8'))
        
    url = "https://tsn.baidu.com/text2audio"
    
    payload='tex=' + encoded_model_reply + '&tok='+ get_access_token() +'&cuid=4XaBWVhw4STcbseSxuok4N1VncpEmOl8&ctp=1&lan=zh&spd=5&pit=5&vol=5&per=1&aue=4'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
    
     # 检查返回类型
    if response.headers.get("Content-Type", "").startswith("audio/"):
        # 返回的是音频流，直接保存
        with open("../pcmfiles/outputPcmData.pcm", "wb") as f:
            f.write(response.content)
        print("---语音合成完成---")
    else:
        # 返回的是错误信息（JSON）
        print("接口返回错误：", response.text)

    # print("---语音合成完成---")
    

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    [API_KEY, SECRET_KEY] = read_config("../configs/textToPcmConfig.txt", API_KEY, SECRET_KEY)
    # print(API_KEY, SECRET_KEY)
    main()
